package com.ujoku.view.builder;

import com.labillusion.core.platform.web.rest.view.BaseViewBuilder;
import com.labillusion.core.util.Convert;
import com.labillusion.core.util.StringUtils;
import com.ujoku.domain.Activity;
import com.ujoku.domain.Favorite;
import com.ujoku.domain.Goods;
import com.ujoku.service.CdnService;
import com.ujoku.view.domain.ActivityView;
import com.ujoku.view.domain.GoodsView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by Andy.Lian on 2015/3/8.
 */
@Component
public class ActivityViewBuilder extends BaseViewBuilder<Goods,GoodsView> {
    @Autowired
    private CdnService cdnService;

    public void ActivityViewBuilder(ActivityView activityView,List<Goods> list, List<Favorite> favoriteList, Date updateTime) throws Exception{
        for(Activity activity:activityView.getActivities()){
            activity.setBanner(cdnService.buildBannerImage(activity.getId(),updateTime.getTime()));

            if(!StringUtils.hasText(activity.getPids()))
                continue;

            String[] pids=activity.getPids().split(",");
            if(pids.length<=0) continue;
            activity.setGoodsViewList(new ArrayList<>());
            for (String pid:pids){
                int id= Convert.toInt(pid,0);
                if(id==0) continue;
                Goods goods=list.stream().filter(g->g.getGoods_id().equals(id)).collect(Collectors.toList()).get(0);
                if(goods!=null){
                    GoodsView goodsView=Create(goods);
                    goodsView.setMediumImage(cdnService.buildGoodsImage(goods.getGoods_id(), CdnService.Goods_Medium, goods.getLast_update().getTime()));
                    setGoodsFav(favoriteList,goodsView);
                    activity.getGoodsViewList().add(goodsView);
                }
            }
        }
    }

    public void setGoodsFav(List<Favorite> favoriteList, GoodsView goodsView){
        if(favoriteList==null || favoriteList.size()<=0) return;
        if(favoriteList.stream().anyMatch(g->g.getGoods_id()==goodsView.getGoods_id())){
            goodsView.setIsFav(true);
        }
    }
}
